package com.android.antelopeapp.network;

import android.content.Context;

import com.android.antelopeapp.constant.ApiConfig;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

/**
 * @author phk
 * copy from google
 * 该类用于进行网络任务的管理
 * 采用单例模式设计，使得该类的生存期处于整个应用打开期间，避免因为activity的变化而停止网络任务
 * 
 */
public class NetworkManager {
	private static NetworkManager mInstance;
	/**请求队列，用于管理网络请求 */
	private RequestQueue mRequestQueue;
	/**图片加载器*/
	private ImageLoader mImageLoader;
	/**应用上下文*/
	private static Context mCtx;
	
	private NetworkManager(Context context){
		mCtx = context;
		mRequestQueue = getRequestQueue();

		mImageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache(
	            LruBitmapCache.getCacheSize(context)));
	}
	
    public static synchronized NetworkManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new NetworkManager(context);
        }
        return mInstance;
    }
	
    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }
    
    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }

    public static String getResourceAbsPath(String relPath){
        if(relPath.startsWith("http://")){
            return relPath;
        }else{
            return ApiConfig.SERVER_RESOURCE+relPath;
        }
    }
    /**返回绝对路径的资源**/
    public static String getGoodsMainPicPath(String relPath){
        return relPath;
    }
}
